import { defineStore } from 'pinia'
import service from '../utils/request'
import { ElMessage } from 'element-plus'

export const useAppointmentStore = defineStore('appointment', {
  state: () => ({
    appointments: [],
    loading: false
  }),
  actions: {
    async fetchPendingAppointments() {
      this.loading = true
      try {
        const response = await service.get('/staff/bookings/pending')
        if (response.data.code === 200) {
          this.appointments = response.data.data
        }
        return response.data
      } catch (error) {
        console.error('获取预约列表失败:', error)
        ElMessage.error('获取预约列表失败')
        throw error
      } finally {
        this.loading = false
      }
    },
    async approveAppointment(id, staffId) {
      try {
        const response = await service.post(
          '/staff/bookings/refund/1',
          { id, staffId }
        )
        return response.data
      } catch (error) {
        console.error('批准预约失败:', error)
        ElMessage.error('批准预约失败')
        throw error
      }
    },
    async rejectAppointment(id, staffId) {
      try {
        const response = await service.post(
          '/staff/bookings/refund/0',
          { id, staffId }
        )
        return response.data
      } catch (error) {
        console.error('拒绝预约失败:', error)
        ElMessage.error('拒绝预约失败')
        throw error
      }
    },
    async fetchAllAppointments(search) {
      this.loading = true
      const parms = { ...search }
      try {
        const response = await service.post('/staff/bookings', parms)
        if (response.data.code === 200) {
          this.appointments = response.data.data
        }
        return response.data
      } catch (error) {
        console.error('获取所有订单失败:', error)
        ElMessage.error('获取所有订单失败')
        throw error
      } finally {
        this.loading = false
      }
    }
  }
})